/**
  * 邮箱
  */
module game {
    export class MailMediator extends BaseMediator {
        public static NAME: string = "MailMediator";
        private gameType: string = "";
        public constructor(viewComponent: any = null) {
            super(MailMediator.NAME, viewComponent);
        }

        public listNotificationInterests(): Array<any> {
            return [
                PanelNotify.HALL.STAGE_RESIZE,
                PanelNotify.HALL.OPEN_MAIL,
                PanelNotify.HALL.CLOSE_MAIL,
                PanelNotify.HALL.REMOVE_ALL_MAIL
            ];
        }
        private panel: MailPanel;
        private showType = null;
        private mailArr: Array<any> = null
        public handleNotification(notification: puremvc.INotification): void {
            this.gameType = notification.getBody();
            switch (notification.getName()) {
                case PanelNotify.HALL.STAGE_RESIZE:
                    if (this.panel) {
                        this.panel.width = GameConfig.curWidth()
                        this.panel.height = GameConfig.curHeight()
                    }
                    break;
                case PanelNotify.HALL.OPEN_MAIL: {
                    this.panel = null;
                    this.panel = new MailPanel();
                    this.showUI(this.panel, 2, 1, true);
                    break;
                }
                case PanelNotify.HALL.CLOSE_MAIL: {
                    this.closePanel(0);
                    //如果所有消息都读完了。关闭大厅的小红点提示
                    if (this.mailArr) {
                        var num = 0;
                        for (var i = 0; i < this.mailArr.length; i++) {
                            if (this.mailArr[i]["nStatus"] == 0 || this.mailArr[i]["nStatus"] == 1) {
                                num++;
                            }
                        }
                        if (num == 0) {
                            this.sendNotification(PanelNotify.HALL.HEID_MAIL_TIP)
                        }
                    }
                    break;
                }
                case PanelNotify.HALL.REMOVE_ALL_MAIL: {
                    this.removeAllMil();
                    break;
                }

            }
        }

        /**
         * 初始化面板ui
         */
        public initUI(): void {
            this.panel.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeButtonClick, this);
            this.panel.gg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.znx.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.all_yidu.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.guanbi.addEventListener(egret.TouchEvent.TOUCH_TAP, this.guanbiClick, this);
            this.panel.all_remove.addEventListener(egret.TouchEvent.TOUCH_TAP, this.removeAllClick, this);
        }

        /**
         * 初始化面板数据
         */
        public initData(): void {
            this.findMail();
        }

        private closeButtonClick(event: egret.TouchEvent): void {
            SoundManage.startAnniuBtnLoad();
            this.closePanel(1);
            //如果所有消息都读完了。关闭大厅的小红点提示
            if (this.mailArr) {
                var num = 0;
                for (var i = 0; i < this.mailArr.length; i++) {
                    if (this.mailArr[i]["nStatus"] == 0 || this.mailArr[i]["nStatus"] == 1) {
                        num++;
                    }
                }
                if (num == 0) {
                    this.sendNotification(PanelNotify.HALL.HEID_MAIL_TIP)
                }
            }
        }
        private findMail() {
            var time = Global.getCurrTimeLong()
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/GameWebApplication/ReadEmail.ashx?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.mailArr = obj["emails"];
                        this.typeClick(null);
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            var data = {
                dwUserID: GameVO.getVo().dwUserID
            }
            EffectUtils.showWaritPanel()
            request.send(JSON.stringify(data));
        }
        //切换站内信和公告
        private typeClick(event: egret.TouchEvent) {
            this.panel.gg.touchEnabled = true
            this.panel.znx.touchEnabled = true
            this.panel.all_yidu.touchEnabled = true
            this.guanbiClick(null);
            if (event == null || event.currentTarget == this.panel.gg) {
                this.panel.gg.icon = "mail_gg"
                this.panel.gg.touchEnabled = false
                this.panel.znx.icon = "mail_znx_s"
                this.showType = 1
                this.showType1()
            } else if (event.currentTarget == this.panel.znx) {
                this.panel.znx.icon = "mail_znx"
                this.panel.znx.touchEnabled = false
                this.panel.gg.icon = "mail_gg_s"
                this.showType = 2
                this.showType2()
            } else if (event.currentTarget == this.panel.all_yidu) {
                this.panel.gg.icon = "mail_gg_s"
                this.panel.znx.icon = "mail_znx_s"
                this.panel.all_yidu.touchEnabled = false
                this.showType = 3
                this.showType3()
            }

        }

        //显示未读公告
        private showType1() {
            this.panel.wushuju.visible = false;
            var leng = this.panel.mail_list.numChildren
            for (var i = 0; i < leng; i++) {
                this.panel.mail_list.getChildAt(i).removeEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
            }
            this.panel.mail_list.removeChildren();
            if (this.mailArr && this.showType != null) {
                for (var i = 0; i < this.mailArr.length; i++) {
                    if (this.mailArr[i]["nStatus"] != 2 && this.mailArr[i]["nType"] == 0) {
                        var mail = new components.emailList(this.mailArr[i])
                        this.panel.mail_list.addChild(mail);
                        mail.addEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
                    }
                }
                if (this.panel.mail_list.numChildren == 0) {
                    this.panel.wushuju.visible = true;
                }
            }
        }
        //显示未读站内信
        private showType2() {
            this.panel.wushuju.visible = false;
            var leng = this.panel.mail_list.numChildren
            for (var i = 0; i < leng; i++) {
                this.panel.mail_list.getChildAt(i).removeEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
            }
            this.panel.mail_list.removeChildren();
            if (this.mailArr && this.showType != null) {
                for (var i = 0; i < this.mailArr.length; i++) {
                    if (this.mailArr[i]["nStatus"] != 2 && this.mailArr[i]["nType"] == 11) {
                        var mail = new components.emailList(this.mailArr[i])
                        this.panel.mail_list.addChild(mail);
                        mail.addEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
                    }
                }
                if (this.panel.mail_list.numChildren == 0) {
                    this.panel.wushuju.visible = true;
                }
            }
        }
        //显示所有已读
        private showType3() {
            this.panel.wushuju.visible = false;
            var leng = this.panel.mail_list.numChildren
            for (var i = 0; i < leng; i++) {
                this.panel.mail_list.getChildAt(i).removeEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
            }
            this.panel.mail_list.removeChildren();
            if (this.mailArr && this.showType != null) {
                for (var i = 0; i < this.mailArr.length; i++) {
                    if (this.mailArr[i]["nStatus"] == 2) {
                        var mail = new components.emailList(this.mailArr[i])
                        this.panel.mail_list.addChild(mail);
                        mail.addEventListener(egret.TouchEvent.TOUCH_TAP, this.openMail, this)
                    }
                }
                if (this.panel.mail_list.numChildren == 0) {
                    this.panel.wushuju.visible = true;
                }
            }
        }
        private openMail(event: egret.TouchEvent) {
            this.panel.guanbi.visible = true;
            this.panel.all_remove.visible = false;
            this.panel.all_yidu.visible = false;
            this.panel.mail_list.visible = false;
            this.panel.mail_vive.visible = true;
            var mail: components.emailList = event.currentTarget;
            this.panel.neirong.text = mail.obj["szMessage"];

            var nStatus = mail.obj["nStatus"];
            if (nStatus != 2) {
                //标记为已读
                mail.obj["nStatus"] = 2;
                var time = Global.getCurrTimeLong()
                var signature = Global.getSynLoginKey(time)
                signature = signature.toUpperCase()
                var request = new egret.HttpRequest();
                request.responseType = egret.HttpResponseType.TEXT;
                request.open(InstructionsEnum.IP_API + "/GameWebApplication/EmailStatusSet.ashx?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                    try {
                        var request = <egret.HttpRequest>event.currentTarget;
                        var obj = JSON.parse(request.response)
                        if (obj.code == 0) {

                        } else {
                            Global.tipShow(obj.msg)
                        }
                    } catch (err) {
                        EffectUtils.textFadeAway("数据包异常，无法解析!")
                    }
                }, this);
                var data = {
                    dwUserID: GameVO.getVo().dwUserID,
                    nStatus: 2,
                    nType: 0,
                    dwMailIds: [mail.obj["dwMail"]]
                }
                request.send(JSON.stringify(data));
            }
        }
        private guanbiClick(event: egret.TouchEvent) {
            this.panel.guanbi.visible = false;
            this.panel.all_remove.visible = true;
            this.panel.all_yidu.visible = true;
            this.panel.mail_list.visible = true;
            this.panel.mail_vive.visible = false;
            if (event != null) {//关闭打开的信封时，刷新信件列表，目的是让刚才打开的信件归类到已读列表
                if (this.showType == 1) {
                    this.showType1()
                } else if (this.showType == 2) {
                    this.showType2()
                } else if (this.showType == 3) {
                    this.showType3()
                }
            }
        }
        //点击删除所有已读
        private removeAllClick() {
            let obj = {
                CODE: PanelNotify.HALL.REMOVE_ALL_MAIL,
                TEXT: "确定要删除所有已读邮件吗？",
            }
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_TIP, obj);
        }
        //确认删除所有已读
        private removeAllMil() {
            var arr = []
            for (var i = 0; i < this.mailArr.length; i++) {
                if (this.mailArr[i]["nStatus"] == 2) {
                    arr.push(this.mailArr[i]["dwMail"])
                }
            }
            var time = Global.getCurrTimeLong()
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/GameWebApplication/EmailStatusSet.ashx?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.findMail();
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            var data = {
                nStatus: -1,
                nType: 0,
                dwMailIds: arr
            }
            request.send(JSON.stringify(data));
        }
    }
}
